package com.letv.business.flow.album;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import com.ledim.app.LeDimApplication;
import com.letv.android.client.LetvSDK;
import com.letv.android.client.constant.LetvSDKConstant;
import com.letv.android.young.client.R;
import com.letv.core.api.LetvRequest;
import com.letv.core.api.MediaAssetApi;
import com.letv.core.bean.DataHull;
import com.letv.core.bean.IVideo;
import com.letv.core.bean.RealPlayUrlInfoBean;
import com.letv.core.bean.TimestampBean;
import com.letv.core.bean.VideoPlayerBean;
import com.letv.core.config.LetvConfig;
import com.letv.core.constant.PlayConstant;
import com.letv.core.db.PreferencesManager;
import com.letv.core.network.volley.VolleyRequest;
import com.letv.core.network.volley.VolleyResponse;
import com.letv.core.network.volley.toolbox.SimpleResponse;
import com.letv.core.network.volley.toolbox.VolleyNoCache;
import com.letv.core.parser.RealPlayUrlInfoParser;
import com.letv.core.parser.VideoPlayerParser;
import com.letv.core.utils.LetvSDKUtils;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.LogInfo;
import com.letv.datastatistics.DataStatistics;
import com.letv.datastatistics.util.LetvErrorCode;
import com.letv.pp.func.CdeHelper;

public class AlbumDownloadFlow extends AlbumPlayFlow {

    private long mVid;
    /**
     * 下载正式地址
     */
    public static final String DYNAMIC_APP_BASE_URL = "http://dynamic.app.m.letv.com/android/dynamic.php";

    /**
     * 下载测试地址
     */
    public static final String TEST_BASE_URL = "http://test2.m.letv.com/android/dynamic.php";


    public AlbumDownloadFlow(Context context, int launchMode, Bundle bundle) {
        super(context, launchMode, bundle);
        mVid = bundle.getLong(PlayConstant.VID);
    }

    @Override
    public void start() {
        LogInfo.log("sguotao", "aid:" + mAid + ",vid:" + mVid + ",cid:" + mCid + ",zid:" + mZid + ",启动模式:" + getLaunchMode());
        startLoadingData();
    }

    @Override
    protected void startLoadingData() {

        requestNetwork();
//        requestDownlaodUrl();
    }


    private void requestNetwork() {
        addPlayInfo("开始请求合并接口", "");

        if (mCid == 0 && mAid == 0 && mZid == 0 && mVid == 0) {
            mLoadListener.requestError(mContext.getString(R.string.commit_error_info), PlayConstant.PlayErrCode.PARAMS_ERROR);
            mObservable.notifyObservers(new AlbumPlayFlowObservable.PlayErrorCodeNotify(PlayConstant.PlayErrCode.PARAMS_ERROR, true));
            return;
        }

        final String uid = PreferencesManager.getInstance(mContext).getUserId();
        final String tm = String.valueOf(TimestampBean.getTm().getCurServerTime());
        String url = MediaAssetApi.getInstance(LeDimApplication.getInstance())
                                  .getVideoPlayUrl(mContext,
                                          mCid + "", mAid + "", mZid + "", mVid + "", uid,
            LetvSDK.getInstance().getVideoFormat(), "0", tm);

        mPlayInfo.videoDispatchConsumeTime = System.currentTimeMillis();
        mPlayInfo.canPlayConsumeTime = System.currentTimeMillis();
        // 接口起始时间（统计动作22 type7使用）
        mPlayInfo.albumPayConsumeTime = System.currentTimeMillis();

        new LetvRequest<VideoPlayerBean>(mContext).setUrl(url).setMaxRetries(MAX_RETRY_TIMES)
            .setCache(new VolleyNoCache()).setParser(new VideoPlayerParser()).setTag(REQUEST_VIDEO_PLAY_URL)
            .setCallback(new SimpleResponse<VideoPlayerBean>() {

                @Override
                public void onNetworkResponse(VolleyRequest<VideoPlayerBean> request, VideoPlayerBean result,
                                              DataHull hull, VolleyResponse.NetworkResponseState state) {
                    mPlayInfo.mRetryNum = request.getRetryPolicy().getRetries();
                    mPlayInfo.videoDispatchConsumeTime = System.currentTimeMillis() - mPlayInfo.videoDispatchConsumeTime;
                    mPlayInfo.albumPayConsumeTime = System.currentTimeMillis() - mPlayInfo.albumPayConsumeTime + sRequestLocalConsumetime;
                    LogInfo.log("sguotao", "****************请求合并接口消耗时间" + mPlayInfo.albumPayConsumeTime + "毫秒****************");
                    if (state == VolleyResponse.NetworkResponseState.SUCCESS) {
                        addPlayInfo("请求合并接口成功", "");
                        result.getVideoFile().getMmsid();
                        Log.i("sguotao", "--->>> mmsid: " + result.getVideoFile().getMmsid());
                        requestDownlaodUrl(result.getVideoFile().getMmsid());
                    } else {
                        addPlayInfo("请求合并接口失败", state + "");
//                        onError(state);
                    }
                }

                @Override
                public void onErrorReport(VolleyRequest<VideoPlayerBean> request, String errorInfo) {
                    DataStatistics.getInstance()
                        .sendErrorInfo(mContext, "0", "0", LetvErrorCode.LTURLModule_UC_MovieAvaiable,
                            null, errorInfo, null, null, null, null);
                }

            }).add();
    }

    private void requestDownlaodUrl(String mmsid) {
        String tm = String.valueOf(TimestampBean.getTm().getCurServerTime());
        String key = TimestampBean.generateVideoFileKey(String.valueOf(mmsid), String.valueOf(tm)); //0 --> mmsid
        String url = MediaAssetApi.getInstance(LeDimApplication.getInstance())
                                  .getDownloadUrl(mContext, mmsid, "no", tm, key, mVid); //0 --> mmsid
        //得到接口地址，再去获取视频的调度地址；调度地址成功之后，在获取真实的下载地址

        new LetvRequest<VideoPlayerBean>(mContext).setUrl(url)
            .setCache(new VolleyNoCache()).setParser(new VideoPlayerParser()).setTag(AlbumPlayFlow.REQUEST_DOWNLOAD)
            .setCallback(
                new SimpleResponse<VideoPlayerBean>() {

                    @Override
                    public void onNetworkResponse(VolleyRequest<VideoPlayerBean> request, VideoPlayerBean result, DataHull hull, VolleyResponse.NetworkResponseState state) {
                        if (state == VolleyResponse.NetworkResponseState.SUCCESS) {
                            LogInfo.log("sguotao", result.getVideoFile().getMp4_350().getMainUrl());

                            String ddUrl = result.getVideoFile().getMp4_350().getMainUrl();

                            StringBuilder mDDUrl = new StringBuilder();
                            mDDUrl.append(ddUrl);
                            mDDUrl.append("&pcode=");
                            mDDUrl.append(LetvConfig.getPcode(mContext));
                            mDDUrl.append("&version=");
                            mDDUrl.append(LetvUtils.getClientVersionName(mContext));
                            mDDUrl.append("&uuid=");
                            mDDUrl.append(LetvUtils.getUUID(mContext));

                            getDownloadUrlByCde(mDDUrl.toString());

                        } else {
                            LogInfo.log("sguotao", "get download url failed.");
                        }
                    }

                }
            ).add();
    }

    private void getDownloadUrlByCde(String ddUrl) {
//        String newddUrl = ddUrl.replace("splatid=346","splatid=356");
        LogInfo.log("sguotao", "防盗链:" + ddUrl);
        addPlayInfo("开始从cde获取下载地址,调度地址", ddUrl);
        LetvSDKUtils.reStartCde(mContext);
        CdeHelper cdeHelper = LetvSDKUtils.getCdeHelper(mContext);
        if (cdeHelper != null) {
            // 加密开关开启,获取加密过后的url
            if (PreferencesManager.getInstance(mContext).isLinkShellSwitch()) {
                String linkshellUrl = LetvSDKUtils.getCdeHelper(mContext).getLinkshellUrl(ddUrl);
                addPlayInfo("从cde获取下载地址,linkShell", linkshellUrl);
                LogInfo.log("sguotao", "linkShell:" + linkshellUrl);

                parseRealDownloadUrl(linkshellUrl);
            }
        }
    }

    private void parseRealDownloadUrl(String ddUrl) {
        new LetvRequest<RealPlayUrlInfoBean>(mContext).setUrl(ddUrl).setCache(new VolleyNoCache())
            .setParser(new RealPlayUrlInfoParser())
            .setRequestType(VolleyRequest.RequestManner.NETWORK_ONLY)
            .setMaxRetries(AlbumPlayFlow.MAX_RETRY_TIMES)
            .setTag(AlbumPlayFlow.REQUEST_VIDEO_PLAY_URL)
            .setCallback(new SimpleResponse<RealPlayUrlInfoBean>() {
                @Override
                public void onNetworkResponse(VolleyRequest<RealPlayUrlInfoBean> request, RealPlayUrlInfoBean result, DataHull hull, VolleyResponse.NetworkResponseState state) {
                    super.onNetworkResponse(request, result, hull, state);
                    if (state == VolleyResponse.NetworkResponseState.SUCCESS) {
                        IVideo mVideo = new IVideo();
                        mVideo.setmDownloadUrl(result.getRealUrl());
                        LetvSDK.getInstance().getCallBack().onEvent(LetvSDKConstant.EVENT_START_DOWNLOAD, "event_start_download", mVideo);
                    }
                }
            }).add();
    }


}
